import { FC, ReactNode, useEffect, useRef, useState } from "react";
import {
  Button,
  Card,
  Cascader,
  Checkbox,
  Col,
  DatePicker,
  Empty,
  Form,
  Input,
  Menu,
  message,
  Popconfirm,
  Row,
  Segmented,
  Select,
  Tag,
} from "antd";
import { useMutation, useQuery } from "@tanstack/react-query";
import { find, forEach, get, isArray, map } from "lodash";
import { DeleteOutlined, PlusOutlined } from "@ant-design/icons";
import { TabTypes } from "../../types/globalSearch";
import { enumToObj, toKeyLabel } from "../../utils/tsf";
import LoadBtn from "../LoadBtn";
import { downloadLink } from "../../utils/download";
import request from "../../utils/request";
import Upload from "../upload";
import SearchPage from "../SearchPage";
import { ContextVal } from "../SearchPage/context";
import MeidaCore from "../MeidaCore";
import Dialog from "../Dialog";
import CaptchInfo from "../CaptchInfo";

enum TaskType {
  全部,
  任务聚合,
}


const GlobalSearchChild: FC<{
  tab: enumToObj;
  headerInfo: ReactNode;
}> = ({ tab, headerInfo }) => {
  const pageCoreRef = useRef<ContextVal>(null)
  // const [tab, setTab] = useState<TabTypes>(TabTypes.人脸);
  const [list, setList] = useState([]);
  const [selected, setSelected] = useState<Set<any>>(new Set());
  const [taskType, _setTaskType] = useState<TaskType>(TaskType[TaskType.全部]);
  const isTaskType2 = taskType === TaskType[TaskType.任务聚合];
  const [selectedTaskId, setSelectedTaskId] = useState<any>(null);

  const  [searchTaskId, setSearchTaskId] = useState(0)

  const ctrlProps = { style: { width: 500 } };

  const { data: taskOptions = [] } = useQuery({
    queryKey: ["taskOptions", searchTaskId],
    queryFn: async () => {
      const data = await request("/task/getPatternList", {
        params: {
          task_id: searchTaskId
        }
      });
      return map(data, (item) => ({
        key: item.id,
        label: item.title,
      }));
    },
  });

  const queryImgListMutation = useMutation({
    mutationFn: async () => {
      const data = await request("/hyqz/search/taskGroupList", {
        method: "POST",
        data: pageCoreRef.current?.getSearchFilter?.(),
      });
      return data;
    },
  });

  const isFirstRenderRef = useRef(true);
  useEffect(() => {
    if (isFirstRenderRef.current) {
      setTimeout(() => {
        isFirstRenderRef.current = false;
      }, 300);
      return;
    }
    pageCoreRef.current?.query?.mutate();
  }, [selectedTaskId, taskType]);

  const { data: fileOptions = [] } = useQuery({
    queryKey: ["fileOptions", searchTaskId],
    queryFn: async () => {
      const data = await request("/task/getFileTypeList", {
        params: {
          task_id: searchTaskId
        }
      });
      return map(data, (item) => ({
        key: item.id,
        label: item.title,
      }));
    },
  });

  const { data: renwuList = [] } = useQuery({
    queryKey: ["renwuList"],
    queryFn: async () => {
      const data = await request("/hyqz/search/getTaskList");
      return map(data, (item) => ({
        key: item.id,
        label: item.title,
      }));
    },
  });

  const { data: elementOptions = [] } = useQuery({
    queryKey: ["elementOptions", searchTaskId],
    queryFn: async () => {
      const data = await request("/pattern/info/element/list", {
        params: {
          task_id: searchTaskId
        }
      });
      return map(data, (group) => ({
        value: group.id,
        label: group.title,
        children: map(group.sub_tag_list, (item) => ({
          value: item.id,
          label: item.title,
        })),
      }));
    },
  });

  const onShowDetail = async (id) => {
    Dialog({
      title: "模型分析",
      width: 1200,
      hideConfirm: true,
      content: <CaptchInfo id={id} />,
    });
  };

  const setTaskType = (changeTaskType: any) => {
    _setTaskType(changeTaskType);
  };

  return (
    <SearchPage
      src="/hyqz/search/page"
      onMount={(v) => (pageCoreRef.current = v)}
      defaultFilters={{
        media_type: tab,
      }}
      pageSizeOptions={[12,24,48]}
      noSearch
      uploadData={(list) => {
        setList(list);
        setSelected(new Set());
      }}
      breadcrumbList={[
        {
          href: "/globalSearch",
          label: "全局搜索",
        },
      ]}
      searchFormat={(data) => {
        const searchElementList = [];
        forEach(data.element_list, (arr) => {
          if (typeof arr === "number") {
            searchElementList.push(arr);
            return;
          }
          if (!isArray(arr)) return;
          if (arr.length === 2) {
            searchElementList.push(arr[1]);
          }
          let item = find(elementOptions, { value: arr[0] });
          if (arr.length === 1 && item) {
            forEach(item?.children, (it) => {
              searchElementList.push(it.value);
            });
          }
        });

        // 任务聚合且选中了目标状态
        if (TaskType[taskType] === TaskType.任务聚合 && selectedTaskId) {
          data.task_id = selectedTaskId;
        }
        data.element_list = searchElementList;
        return data;
      }}
    >
      {headerInfo}
      <SearchPage.Search
        layout="block"
        labelCol={{
          flex: "80px 0 0",
        }}
        onHandleSearch={() => {
          setSelectedTaskId(null);
          queryImgListMutation.mutate();
        }}
        actions={[
          <Button
            type="primary"
            size="small"
            onClick={async () => {
              setSelected(new Set(list.map((item) => item.media_id)));
            }}
          >
            全选
          </Button>,
          <LoadBtn
            type="primary"
            size="small"
            onClick={async () => {
              const { url } = await request.post("/task/downloadMedia", {
                media_id: [...selected],
              });
              downloadLink(url);
            }}
          >
            下载选中
          </LoadBtn>,
          <LoadBtn
            type="primary"
            size="small"
            onClick={async () => {
              const media_id = await request.post(
                "/hyqz/search/getMediaList",
                pageCoreRef.current?.getSearchFilter?.()
              );
              const { url } = await request.post("/task/downloadMedia", {
                media_id,
              });
              downloadLink(url);
            }}
          >
            下载全部
          </LoadBtn>,
        ]}
        extraHeader={
          <>
            <Form.Item noStyle dependencies={['task_id']}>
              {(instance) => {
                const curTaskId = instance.getFieldValue('task_id');
                setSearchTaskId(() => {
                  return curTaskId
                })
                return null;
              }}
            </Form.Item>
            {[TabTypes.人脸, TabTypes.图像].includes(tab) && (
              <Form.Item
                name="url"
                style={{ marginBottom: 16, width: "100%" }}
                className="circleUploadItem"
              >
                <Upload
                  maxCount={1}
                  hideLoadingNative={true}
                  style={{
                    width: 45,
                    height: 45,
                  }}
                  // validateData={async (url) => {
                  //   if (tab === TabTypes.人脸) {
                  //     await request(`/hyqz/validate/face?url=${url}`, {
                  //       method: "post",
                  //     });
                  //   }
                  // }}
                  listType="picture-card"
                  accept=".webp, .svg, .png, .gif, .jpg, .jpeg"
                >
                  <PlusOutlined />
                </Upload>
              </Form.Item>
            )}
            {[TabTypes.标签].includes(tab) && (
              <Form.Item name="element_list" label="元素标签">
                <Cascader
                  {...ctrlProps}
                  multiple
                  options={elementOptions}
                  maxTagCount="responsive"
                  placeholder="请选择元素标签"
                />
              </Form.Item>
            )}
            {[TabTypes.人脸].includes(tab) && (
              <Form.Item name="time" label="创建时间">
                <DatePicker.RangePicker {...ctrlProps} />
              </Form.Item>
            )}
            {[TabTypes.文字].includes(tab) && (
              <Form.Item name="include" label="包含">
                <Input {...ctrlProps} placeholder="请输入包含" />
              </Form.Item>
            )}
            {[TabTypes.标签].includes(tab) && (
              <Form.Item name="pattern_info" label="业务模型">
                <Select
                  {...ctrlProps}
                  mode="multiple"
                  placeholder="请选择业务模型"
                >
                  {map(taskOptions, (item) => (
                    <Select.Option key={item.key}>{item.label}</Select.Option>
                  ))}
                </Select>
              </Form.Item>
            )}
            <Form.Item name="task_id" label="任务选择">
              <Select {...ctrlProps} placeholder="请选择任务选择">
                {map(renwuList, (item) => (
                  <Select.Option key={item.key}>{item.label}</Select.Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item name="media_type_list" label="数据类型">
              <Select
                {...ctrlProps}
                mode="multiple"
                placeholder="请选择数据类型"
                maxTagCount="responsive"
              >
                {map(fileOptions, (item) => (
                  <Select.Option key={item.key}>{item.label}</Select.Option>
                ))}
              </Select>
            </Form.Item>
          </>
        }
      />
      <div className="my-[10px] flex h-[30px] ">
        <div className="flex flex-1">
          <Segmented
            options={toKeyLabel(enumToObj(TaskType)).map((v) => v.label)}
            value={taskType.toString()}
            onChange={setTaskType}
          />
        </div>
      </div>
      <SearchPage.Cont className="my-10 flex">
        {isTaskType2 && (
            <Menu
              style={{ width: 250 }}
              mode="inline"
              selectedKeys={[selectedTaskId]}
              onClick={(item) => {
                setSelectedTaskId(item?.key);
              }}
              items={map(queryImgListMutation.data, (item) => ({
                key: item.task_id,
                label: `${item.task_name} ${item.media_hit_num}`,
              }))}
            />
        )}
        {get(list, "length", 0) === 0 && (
          <div className="flex-1">
            <Empty />
          </div>
        )}
        {get(list, "length", 0) !== 0 && (
          <Row
            gutter={[12, 12]}
            style={
              isTaskType2
                ? {
                    flex: "1",
                  }
                : { width: (350 + 12 * 2) * 4, margin: "auto" }
            }
          >
            {list.map((item) => (
              <Col>
                <Card
                  hoverable
                  style={{ width: 350, cursor: "pointer" }}
                  cover={(() => {
                    if (item.media_type === "video") {
                      return (
                        <div
                          onClick={(e) => {
                            e.stopPropagation();
                          }}
                          className="pointer-events-none"
                        >
                          <MeidaCore
                            source={item.cover_url}
                            type="video"
                            pointList={[]}
                            width={350}
                            height={300}
                          />
                        </div>
                      );
                    }
                    return (
                      <img
                        style={{ width: 350, height: 300, objectFit: "cover" }}
                        src={item.cover_url}
                      />
                    );
                  })()}
                  onClick={() => {
                    onShowDetail(item.media_id);
                  }}
                  bodyStyle={{
                    padding: 5,
                    paddingLeft: 5,
                    height: 50,
                    display: "flex",
                    alignItems: "center",
                  }}
                >
                  <div className="flex flex-none">
                    <div
                      className="mr-[5px] inline-block"
                      onClick={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        selected.has(item.media_id)
                          ? selected.delete(item.media_id)
                          : selected.add(item.media_id);
                        setSelected(new Set(selected));
                      }}
                    >
                      <Checkbox checked={selected.has(item.media_id)} />
                    </div>
                    <div
                      className="inline-block"
                      onClick={(e) => {
                        e.stopPropagation();
                      }}
                    >
                      <Popconfirm
                        title="删除"
                        onConfirm={async () => {
                          await request.delete(`/task/media/${item.media_id}`);
                          message.success("删除成功");
                          pageCoreRef.current?.query?.mutate(null);
                        }}
                        okText="确定"
                        cancelText="取消"
                      >
                        <DeleteOutlined />
                      </Popconfirm>
                    </div>
                  </div>
                  {!item.is_hit && (
                    <div className="flex items-center justify-center flex-1">
                      正常
                    </div>
                  )}
                  {item.is_hit && (
                    <div className="flex flex-wrap pl-[5px] overflow-y-auto max-h-full flex-1 justify-center">
                      {map(item.pattern_info, (v) => (
                        <Tag className="m-[2px]">
                          {v?.pattern_name}({v?.hit_score}/{v?.total_score})
                        </Tag>
                      ))}
                    </div>
                  )}
                </Card>
              </Col>
            ))}
          </Row>
        )}
      </SearchPage.Cont>
    </SearchPage>
  );
};

export default GlobalSearchChild;
